package com.raychi.demo.action;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;
import com.raychi.demo.entity.Category;
import com.raychi.demo.entity.Product;
import com.raychi.demo.service.CategoryService;
import com.raychi.demo.service.ProductService;
import com.raychi.demo.util.JdbcUtil;
import com.raychi.demo.util.ProductUtil;

public class ProductAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	
	private List<Product> list;
	private List<Category> categories;
	private Product product;
	private ProductService productService;
	private CategoryService categoryService;

	public String list() throws ClassNotFoundException, SQLException{
		list = productService.getProducts();
		return "list";
	}
	
	public String input(){
		categories = categoryService.getCategorys();
		return "input";
	}
	
	public String save() throws ClassNotFoundException, SQLException{
		productService.save(product);
		return list();
	}
	
	public String delete() throws ClassNotFoundException, SQLException{
		productService.delete(product);
		return list();
	}
	
	public String edit(){
		product = getProductById(product.getId());
		return "edit";
	}
	
	public String update() throws ClassNotFoundException, SQLException{
		productService.update(product);
		return list();
	}

	
	public Product getProductById(int id) {
		Product product = null;
		Connection conn = null;
		try {
			conn = JdbcUtil.getConnection();
			Statement st = conn.createStatement();
			String sql = "select * from product where id=" + id;
			ResultSet rs = st.executeQuery(sql);
			while (rs.next()) {
				product = ProductUtil.createProduct(rs);
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (conn != null)
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
		}
		return product;
		
	}

	public List<Product> getList() {
		return list;
	}

	public void setList(List<Product> list) {
		this.list = list;
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public void setCategoryService(CategoryService categoryService) {
		this.categoryService = categoryService;
	}

	public List<Category> getCategories() {
		return categories;
	}

	public void setCategories(List<Category> categories) {
		this.categories = categories;
	}
	
}
